package cn.com.zsw.gblog.modules.gblog.service.impl;

import cn.com.zsw.gblog.config.cache.RedisCache;
import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.gblog.dto.CommentSubmitDTO;
import cn.com.zsw.gblog.modules.gblog.entity.GbCommentEntity;
import cn.com.zsw.gblog.modules.user.entity.GbUserEntity;
import cn.com.zsw.gblog.modules.gblog.mapper.GbCommentMapper;
import cn.com.zsw.gblog.modules.gblog.mapper.GbPostsMapper;
import cn.com.zsw.gblog.modules.gblog.service.GbCommentService;
import cn.com.zsw.gblog.modules.user.service.GbUserService;
import cn.com.zsw.gblog.utils.DozerBeanUtils;
import cn.com.zsw.gblog.utils.JwtUtils;
import cn.com.zsw.gblog.modules.gblog.vo.CommentVO;
import cn.com.zsw.gblog.modules.gblog.vo.CommentsPageVO;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//import cn.com.zsw.gblog.utils.HttpUtils;

/**
 * (GbComment)表服务实现类
 *
 * @author shiwangzhou
 * @since 2020-06-22 16:26:14
 */
@Slf4j
@Service("gbCommentService")
public class GbCommentServiceImpl extends ServiceImpl<GbCommentMapper,
        GbCommentEntity> implements GbCommentService {
    @Autowired
    RedisCache redisCache;
    @Autowired
    GbUserService userService;
    @Resource
    private GbCommentMapper gbCommentMapper;
    @Resource
    private GbPostsMapper gbPostsDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public GbCommentEntity queryById(String id) {
        return this.gbCommentMapper.selectById(id);
    }

    /**
     * @param postId
     * @Author: shiwangZhou
     * @Description: 查询文章下的评论
     * @Date: 2020-06-22 16:40
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<cn.com.zsw.gblog.entity.GbComment>
     * @Param commentsPageDTO
     */
    @Override
    public List<CommentsPageVO> selectListPage(String postId) {
        LambdaQueryWrapper<GbCommentEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GbCommentEntity::getPostId, postId);
        List<GbCommentEntity> records = gbCommentMapper.selectList(wrapper);
        List<GbCommentEntity> parentList = records.stream().filter(gbComment -> gbComment.getParentId()==null).collect(Collectors.toList());
        List<GbCommentEntity> noParentList = records.stream().filter(gbComment -> gbComment.getParentId()!=null).collect(Collectors.toList());
        List<CommentsPageVO> commentsPageVOList = new ArrayList<>();
        for (GbCommentEntity gbComment : parentList) {
            CommentsPageVO commentsPageVO = new CommentsPageVO();
            List<CommentVO> reply = noParentList.stream().filter(gbComment1 -> gbComment.getId().equals(gbComment1.getParentId()))
                    .map(gbComment1 -> DozerBeanUtils.copy(gbComment1, CommentVO.class
                    )).collect(Collectors.toList());
            CommentVO commentVO = DozerBeanUtils.copy(gbComment, CommentVO.class);
            commentsPageVO.setComment(commentVO);
            commentsPageVO.setReply(reply);
            commentsPageVOList.add(commentsPageVO);
        }
        return commentsPageVOList;
    }

    /**
     * @param commentSubmitDTO
     * @Author: shiwangZhou
     * @Description: 提交评论
     * @Date: 2020-06-23 10:42
     * @Return void
     * @Param commentSubmitDTO
     */
    @Override
    public Long submitReply(CommentSubmitDTO commentSubmitDTO) {

        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            return null;
        }
        HttpServletRequest request = attrs.getRequest();
        String header = request.getHeader("X-Token");
        if (StringUtils.isBlank(header)) {
            return null;
        }
        String token = redisCache.getCacheObject(SysConstants.REDIS_JWT_TOKEN_ID + header);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Claims claims = JwtUtils.getTokenBody(header);
        if (claims == null) {
            return null;
        }
        log.info("claims：" + claims);
//            获取用户名
        String userId = claims.getSubject();
        GbUserEntity gbUserEntity = userService.getById(userId);

        GbCommentEntity comment = DozerBeanUtils.copy(commentSubmitDTO, GbCommentEntity.class);
        Long id = IdUtil.createSnowflake(1, 1).nextId();
        comment.setId(id);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());

        comment.setFromUserAvatar(gbUserEntity.getAvatar());
        comment.setFromUserId(gbUserEntity.getId());
        comment.setFromUserName(gbUserEntity.getUsername());
        gbCommentMapper.insert(comment);
        gbPostsDao.increaseComment(commentSubmitDTO.getPostId());
        log.debug(JSON.toJSONString(comment));
        return id;
    }
}